package cn.qingyun.gis.modules.express.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.qingyun.gis.exception.CommonException;
import cn.qingyun.gis.modules.express.entity.HwQuery;
import cn.qingyun.gis.modules.express.request.HwGetGridIdRequest;
import cn.qingyun.gis.modules.express.request.HwGetTokenRequest;
import cn.qingyun.gis.modules.express.response.HwGridByNumResponse;
import cn.qingyun.gis.modules.express.service.IHwRestApiService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;

@Slf4j
@Service
public class HwRestApiServiceImpl implements IHwRestApiService {

    @Value("${qingyun.hw.service-host:http://127.0.0.1}")
    private String hwHost;

    @Value("${qingyun.grid.service-host:http://127.0.0.1}")
    private String hwGridHost; // 华为-网格内网测试地址

    @Override
    public String gridBoundaryQuery(HwQuery hwQuery) {
        JSONObject param = JSONUtil.createObj();
        log.debug("传入字段code：{}", hwQuery.getCode());
        param.put("code", hwQuery.getCode());
        HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
        headers.put("Content-Type", "application/json;charset=UTF-8");
        String requestUrl = String.format("%s:55501/SDCommon/v1/resource/qryBoundaryRes", hwGridHost);
        try {
            HttpResponse response = HttpUtil.createPost(requestUrl).addHeaders(headers)
                    .body(String.valueOf(param))
                    .timeout(1000)
                    .execute();

            if (response.isOk()) {
                String res = JSONUtil.parseObj(response.body()).getByPath("result.bundary").toString();
                log.debug("输出返回结果 {}", res);
                return res;
            }
        } catch (Exception e) {
            log.error("华为-网格边界查询询接口 {}", requestUrl, e);
        }
        return null;
    }

    @Override
    public JSONObject gridResourceQuery(HwQuery hwQuery) {
        JSONObject param = JSONUtil.createObj();
        log.debug("传入字段code：{}", hwQuery.getCode());
        log.debug("传入字段resource：{}", hwQuery.getResource());
        log.debug("传入字段type：{}", hwQuery.getType());
        param.put("code", hwQuery.getCode());
        param.put("resource", hwQuery.getResource());
        param.put("type", hwQuery.getType());
        HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
        headers.put("Content-Type", "application/json;charset=UTF-8");
        String requestUrl = String.format("%s:55501/SDCommon/v1/resource/qryResource", hwGridHost);
        try {
            String res = HttpUtil.post(requestUrl, param.toString(), 1000);
            log.debug("输出返回结果 {}", res);
            if (StrUtil.isNotEmpty(res)) {
                return JSONUtil.parseObj(res);
            }
        } catch (Exception e) {
            log.error("华为-网格资源查询询接口 {}", requestUrl, e);
        }
        return null;
    }


    @Override
    public List<HwGridByNumResponse> getGridByAccountTest(HwGetGridIdRequest hwQuery) {
        JSONObject param = JSONUtil.createObj();
        log.debug("传入字段type：{}", hwQuery.getType());
        log.debug("传入字段crmAccount：{}", hwQuery.getCrmAccount());
        log.debug("传入字段areaCode：{}", hwQuery.getAreaCode());

        param.put("type", hwQuery.getType());
        param.put("crmAccount", hwQuery.getCrmAccount());
        param.put("areaCode", hwQuery.getAreaCode());

        HashMap<String, String> headers = new HashMap<>();//存放请求头，可以存放多个请求头
        headers.put("Content-Type", "application/json;charset=UTF-8");
        String requestUrl = String.format("%s:55501/SDCommon/v1/nk/producer/grid/list ", hwGridHost);

        try {
            HttpResponse response = HttpUtil.createPost(requestUrl).addHeaders(headers).body(String.valueOf(param))
                    .timeout(1000).execute();
            log.debug("输出返回结果 {}", response.body());
            // 返回成功
            if ("0".equals(JSONUtil.parseObj(response.body()).getByPath("res_code"))) {
                JSONArray jsonArray = JSONUtil.parseArray(JSONUtil.parseObj(response.body()).getByPath("result").toString());
                return JSONUtil.toList(jsonArray, HwGridByNumResponse.class);
            }
            // 接口报500
            if ("500".equals(JSONUtil.parseObj(response.body()).getByPath("status"))) {
                throw new CommonException("当前工号配置区域编码已失效，请联系地市工号管理人员处理");
            }
        } catch (Exception e) {
            throw new CommonException("接口调用出错，请联系相关人员");
        }
        return null;
    }

    @Override
    public String getToken(HwGetTokenRequest request) {
        JSONObject param = JSONUtil.createObj();
        // 定义请求体
        log.debug("传入字段grant_type：{}", request.getGrantType());
        log.debug("传入字段client_id：{}", request.getClientId());
        log.debug("传入字段client_secret：{}", request.getClientSecret());
        log.debug("传入字段token_type：{}", request.getTokenType());
        param.put("grant_type", request.getGrantType());
        param.put("client_id", request.getClientId());
        param.put("client_secret", request.getClientSecret());
        param.put("token_type", request.getTokenType());
        // 定义请求头
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Accept", "application/json");
        // 定义请求链接
        String requestUrl = String.format("%s/openapi/restOauth2Server/access_token", hwHost);
        try {
            HttpResponse response = HttpUtil.createPost(requestUrl).addHeaders(headers).body(String.valueOf(param)).timeout(1000).execute();
            log.debug("输出返回结果 {}", response.body());
            if (response.isOk()) {
                return JSONUtil.parseObj(response.body()).getByPath("access_token").toString();
            }
        } catch (Exception e) {
            log.error("华为-获取token {}", requestUrl, e);
        }
        return null;
    }

    @Override
    public JSONObject getGridByAccount(HwGetGridIdRequest request) {
        JSONObject param = JSONUtil.createObj();
        log.debug("传入字段type：{}", request.getType());
        log.debug("传入字段crmAccount：{}", request.getCrmAccount());
        param.put("type", request.getType());
        param.put("crmAccount", request.getCrmAccount());
        // 定义请求头
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json;");
        String requestUrl = String.format("%s/openapi/ISSSService?method=qryGridInfoList&access_token=%s&format=json&version=1.0.0", hwHost, request.getToken());
        try {
            HttpResponse response = HttpUtil.createPost(requestUrl).addHeaders(headers).body(String.valueOf(param)).timeout(1000).execute();
            log.debug("输出返回结果 {}", response.body());
            if (response.isOk()) {
                return JSONUtil.parseObj(response.body());
            }
        } catch (Exception e) {
            log.error("华为-获取网格编码接口 {}", requestUrl, e);
        }
        return null;
    }
}
